<?php

namespace liketp;

use liketp\database\Query;
use liketp\database\Raw;

class DatabaseManager
{
    protected $app;
    protected $config = [];

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function __call($method, $arguments)
    {
        return call_user_func_array([$this->connect(), $method], $arguments);
    }

    public function connect(string $dbType = '', array $config = [])
    {
        $this->config = $this->connectConfig($dbType, $config);
        return $this->createQuery()->connect($this->config);
    }

    public function config(string $key = '', $default = null)
    {
        if (empty($key)) {
            return $this->config;
        } else {
            return $this->config[$key] ?? $default;
        }
    }

    public function raw($sqlPartment)
    {
        return new Raw($sqlPartment);
    }


    //------------------------------------------------ protected
    protected function createQuery()
    {
        return new Query($this->app, $this);
    }

    protected function connectConfig($dbType, $config): array
    {
        $databaseConfig = config('database');
        $dbType = $dbType ?: $databaseConfig['default'];
        $connections = $databaseConfig['connections'] ?? [];

        if (isset($connections[$dbType]) == false) {
            $msg = 'The data type "' . $dbType . '" is not in config file.';
            throw new \InvalidArgumentException($msg);
        }
        $typeConfig = $connections[$dbType];
        $fullConfig = $config + $typeConfig;

        return $fullConfig;
    }
}
